package com.example.newinfinity.View.DrawShape

import android.graphics.Canvas
import kotlin.math.PI
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin

//画箭头
class ArrowShape() : Shape() {
    override fun draw(canvas: Canvas) {
        val dx = endX - startX
        val dy = endY - startY

        // 如果起点终点重合则不绘制箭头
        if (dx == 0f && dy == 0f) return

        val angle = atan2(dy.toDouble(), dx.toDouble())
        val headLength = 40.0 // 箭头头长度
        val headAngle = Math.toRadians(10.0) // 箭头头角度30度

        // 计算箭头头两个点的坐标
        val point1 = calculateArrowPoint(endX, endY, angle + PI - headAngle, headLength)
        val point2 = calculateArrowPoint(endX, endY, angle + PI + headAngle, headLength)

        // 绘制主线段
        canvas.drawLine(startX, startY, endX, endY, mPaint)
        // 绘制箭头头
        canvas.drawLine(endX, endY, point1.first, point1.second, mPaint)
        canvas.drawLine(endX, endY, point2.first, point2.second, mPaint)

        //继承父类 拖拉点拽状态为selected时显示边框及四个拖拉圆点
        super.draw(canvas)
    }

    override fun containsPointInPath(x: Float, y: Float): Boolean {
        val a = (startX - x) * (startX - x) + (startY - y) * (startY - y)
        val reallyA = Math.sqrt(a.toDouble())
        val b = (endX - x) * (endX - x) + (endY - y) * (endY - y)
        val reallyB = Math.sqrt(b.toDouble())
        val lineLength = (startX - endX) * (startX - endX) + (startY - endY) * (startY - endY)
        val reallyLineLength = Math.sqrt(lineLength.toDouble())
        return if (reallyA + reallyB < reallyLineLength + 1) {
            true
        } else {
            false
        }
        /*return super.containsPoint(x, y)*/
    }

    private fun calculateArrowPoint(
        x: Float,
        y: Float,
        angle: Double,
        length: Double
    ): Pair<Float, Float> {
        return Pair(
            (x + length * cos(angle)).toFloat(),
            (y + length * sin(angle)).toFloat()
        )
    }
}